<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\Corp\Action\Callback;

use EasyWeChat\Factory;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\Codec\Json;
use Hyperf\Utils\Context;
use MoChat\App\Common\Exception\CommonException;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use Psr\Http\Message\ServerRequestInterface;

/**
 * 第三方服务商通用回调.
 *
 * @Controller
 */
class Provider extends AbstractAction
{
    /**
     * @var \Psr\Log\LoggerInterface
     */
    private $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        $this->logger = $loggerFactory->get(__CLASS__);
    }

    /**
     * @RequestMapping(path="/callback/corp/provider", methods="GET,POST")
     */
    public function handle()
    {
        try {
            $config = $this->getConfig();
            $this->reloadRequest($config);

            $workApp = Factory::openWork($config);
            /** @var \EasyWeChat\OpenWork\Application $workApp */
            $workApp = rebind_app($workApp, $this->request);
            $params = $this->request->all();
            $decParams = $workApp->server->getMessage();
            $this->logger->info(sprintf('第三方服务商通用回调接收成功，加密信息[%s]，解密信息[%s]', Json::encode($params), Json::encode($decParams)));

            $response = $workApp->server->serve();
            return $response->getContent();
        } catch (\Exception $e) {
            $this->logger->error(sprintf('第三方服务商通用回调失败，错误信息[%s]', $e->getMessage()));
        }
        return 'error';
    }

    /**
     * 获取配置.
     */
    private function getConfig(): array
    {
        $providerConfig = config('framework.wework.provider');
        if (empty($providerConfig) || empty($providerConfig['corp_id'])) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '企业微信服务商配置为空');
        }

        return [
            'corp_id' => $providerConfig['corp_id'],
            'secret' => $providerConfig['secret'],
            'token' => $providerConfig['token'],
            'aes_key' => $providerConfig['aes_key'],
        ];
    }

    /**
     * 重置请求
     */
    private function reloadRequest(array $config): void
    {
        if ($this->request->isMethod('POST')) {
            return;
        }

        if (empty($corData)) {
            return;
        }
        $request = Context::get(ServerRequestInterface::class)->withQueryParams(array_merge($this->request->query(), [
            'ToUserName' => $config['corp_id'],
        ]));
        Context::set(ServerRequestInterface::class, $request);
    }
}
